﻿using Microsoft.AspNetCore.Http;
using TianShu.Domain;
using TianShu.Domain.Repositories;
using TianShu.Service.Contracts.Service.Crud;
using TianShu.Service.Dtos;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using TianShu.Domain.Entities;
using System.Linq.Expressions;

namespace TianShu.Service.Services.Crud
{
    public abstract class QueryServiceImpl<TEntity, TKey, TListDto> : BaseServiceImpl<TEntity, TKey>, IQueryService<TListDto>
         where TEntity : class, IEntity<TKey>, new()
         where TListDto : class, IEntityDto
    {
        public QueryServiceImpl()
        {
        }

        public virtual async Task<PageResultDto<IEnumerable<TListDto>>> GetUrlParamAsync(List<UrlParams> urlParams)
        {
            var whereCondition = GetQueryWhereCondition(urlParams);
            var queryResult = await EntityRepository.GetListAsync(urlParams, whereCondition);
            var data = ObjectMapper.Map<IEnumerable<TEntity>, IEnumerable<TListDto>>(queryResult.Item1);
            return new PageResultDto<IEnumerable<TListDto>>(data, queryResult.Item2);
        }

        public virtual Expression<Func<TEntity, bool>> GetQueryWhereCondition(List<UrlParams> urlParams)
        {
            Expression<Func<TEntity, bool>> expression = e => true;
            return expression;
        }
    }
    public abstract class QueryServiceImpl<TEntity, TKey, TListDto, TDetail> : QueryServiceImpl<TEntity, TKey, TListDto>
         where TEntity : class, IEntity<TKey>, new()
         where TListDto : class, IEntityDto

    {
        protected QueryServiceImpl()
        {
        }


        public virtual async Task<PageResultDto<TDetail>> GetByIdAsync(TKey id)
        {
            var entity = await EntityRepository.FindAsync(id);
            if (entity == null)
            {
                return new PageResultDto<TDetail>("数据不存在，请刷新");
            }
            var data = ObjectMapper.Map<TEntity, TDetail>(entity);
            return new PageResultDto<TDetail>(data);
        }

    }
}
